package erbedo.tvfinder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import erbedo.tvfinder.db.DBAdapter;

import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class TVFinder extends ListActivity {
	
	URLConnection feedUrl;
	InputStream in;
	String json;
	JSONArray valArray, programsArray;
		
	private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
        StringBuilder sb = new StringBuilder();
     
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return sb.toString();
    }
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    	
        DBAdapter db = new DBAdapter(this);
        db.open();
    	db.cleanDb();
        
        // Logic
        // get program list
        
        // Example
		String url = "http://guidatv.sky.it/app/guidatv/contenuti/data/grid/10_03_11/ch_101.js";
        //TextView tv = (TextView)findViewById(R.id.mainlabel);
		
        try {
        	feedUrl = new URL(url).openConnection();
        } catch (MalformedURLException e) {
        	Log.v("ERROR","MALFORMED URL EXCEPTION");
        } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        try {
        	in = feedUrl.getInputStream();

            json = convertStreamToString(in);
            JSONObject j = new JSONObject(json);
            

//            tv.setText(j.toString());
            JSONArray nameArray = j.names();
            
            valArray = j.toJSONArray(nameArray);
            
            programsArray = j.getJSONArray(nameArray.get(1).toString());
//            JSONArray sampleProgramNames = programsArray.get(1);
//            Log.v("222",sampleProgramNames.getString(2));
            for (int i = 0; i < programsArray.length(); i++) {
            	String array = programsArray.getString(i);
            	JSONObject k = new JSONObject(array);
            	
//            	Log.i("VALUES",k.optString("id","1")+k.optString("title", "defaultValue"));
            	long id = k.optLong("id",1);
            	String title = k.optString("title","Titolo non trovato");
            	String desc = k.optString("desc","Descrizione non trovata");
//            	Log.i("SCATAFASCIO",String.valueOf(id));
            	db.insertProgram(id, title, desc);
            	//db.insertId(id);
            }
            Log.i("JSON ARRAY",programsArray.getString(2).toString());
            JSONObject program = new JSONObject(programsArray.toString().replace("[", "").replace("]", ""));
            Log.i("JSON OBJECT",program.toString());
            JSONArray programNames = program.names();
            JSONArray programValues = program.toJSONArray(programNames);
            
//            for (int i = 0; i<programValues.length(); i++) {
//            	Log.i(programNames.getString(i),programValues.getString(i).toString());
//            }

            Cursor c = db.getAllPrograms();
            
//            Log.i("TITLE",c.getString(1));
//            Toast.makeText(this, c.getString(1), Toast.LENGTH_LONG);
            
            String[] mStrings = new String[50];
            
            int i = 0;
//            Log.i("OPOP",String.valueOf(c.getCount()));
//            c.moveToPosition(2);
//            Log.i("OPOP",c.getString(0));
//            Toast.makeText(this, c.toString(), Toast.LENGTH_LONG);
//            c.moveToFirst();
            
            if (c != null) { 
            	Log.i("c","NOTNULL");
                if (c.moveToFirst()) {
                	Log.i("c","FIRST");
                     int lol = 0; 
                     /* Loop through all Results */ 
                     do { 
                           
                          /* Retrieve the values of the Entry 
                           * the Cursor is pointing to. */ 
                    	  Log.i("c","PRIMA");
                    	  Log.i("c",c.getString(1).toString());
                          String title = c.getString(c.getColumnIndex("title"));
                          Log.i("c","DOPO title = " + title);
                          /* We can also receive the Name 
                           * of a Column by its Index. 
                           * Makes no sense, as we already 
                           * know the Name, but just to shwo we can  */ 
                          mStrings[lol++] = title;
//                          Log.i("STRINGS",mStrings[lol++]);
                     } while (c.moveToNext()); 
                } 
           }
            
//            while (!(c.isLast())) {
//            	mStrings[i++] = c.getString(1);
//            	c.moveToNext();
//            }

            // Create an ArrayAdapter, that will actually make the Strings above appear in the ListView 
            this.setListAdapter(new ArrayAdapter<String>(this, 
                             android.R.layout.simple_list_item_1, mStrings)); 
            
        } catch (Exception e) {
			e.printStackTrace();
        }
        
//        tv.setText(valArray.toString());
//        tv.setText(json);

        // Example end
        
        //	from net
        //	from db
        // display it
        // if user searches
        //	look for matchups
        // 	display them
        // every 1h look for new days
    }
}